package com.itheima.tlias.tliasweb.filter;


import com.alibaba.fastjson2.JSON;
import com.itheima.tlias.tliasweb.Constants;
import com.itheima.tlias.tliasweb.pojo.Result;
import com.itheima.tlias.tliasweb.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        // 先获取请求的url
        String requestURI = req.getRequestURI();
        log.info("LoginCheckFilter， uri:{}", requestURI);
        // 判断是否是登录/login
        if(requestURI.contains("/login")){
            // 是登录，直接放行
            chain.doFilter(request, response);
        }else{
            // 不是登录，从请求头中获取token
            String token = req.getHeader("token");
            // token为空，失败
            if(!StringUtils.hasLength(token)){
                // 失败
                returnError(res);
            }else{
                try{
                    // token非空，解析token
                    Claims claims = JwtUtils.parseJWT(token);
                    Integer id = claims.get(Constants.ID, Integer.class);
                    String username = claims.get(Constants.USERNAME, String.class);
                    log.info("id：{}， username:{}", id, username);
                    if(id != null && id > 0 && StringUtils.hasLength(username)){
                        // 解析成功 放行
                        chain.doFilter(request, response);
                    }else{
                        // 解析失败， 失败
                        // 失败
                        returnError(res);
                    }
                }catch(Exception e){
                    log.error("token解析异常", e);
                    // 失败
                    returnError(res);
                }
            }
        }
    }
    private void returnError(HttpServletResponse res) throws IOException{
        // 设置响应头中的code
        res.setStatus(200);
        // 设置响应体的数据格式
        res.setContentType("application/json;charset=utf8");
        // 设置响应数据
        Result result = Result.error("NOT_LOGIN");
        String json = JSON.toJSONString(result);
        // 把数据写入到浏览器的响应
        res.getWriter().write(json);
    }
}
